class Category < ActiveRecord::Base
  has_many :posts
  
  validates_presence_of :title
  
  def find_avalaible_posts(start_date, end_date)
    conflicting_reservations = Reservation.find(:all, :conditions => ['((end_date >= ? AND end_date <= ?) OR (start_date >= ? AND start_date <= ?) OR (start_date <= ? AND end_date >= ?)) AND state = ?',  start_date, end_date, start_date, end_date, start_date, end_date, 'paid'])

    #array of taken post_ids
    busy_posts = conflicting_reservations.collect{ |res| res.post_id }
    if busy_posts and busy_posts.size > 0
      avalaible_posts = Post.find(:all, :conditions => ['category_id = ? AND id NOT IN (?)', self.id, busy_posts], :order => 'posts.title ASC')
    else
      avalaible_posts = Post.find(:all, :conditions => ['category_id = ?', self.id], :order => 'posts.title ASC')
    end
    avalaible_posts
  end
  
end
